package com.tavenli.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tavenli.entity.F18Device;
import com.tavenli.services.DeviceCmdService;
import com.tavenli.services.F18DeviceService;
import com.tavenli.services.IClockService;

@Controller
@RequestMapping("/iclock")
public class IClockController {
	private static Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	@Autowired
	private IClockService clockService;
	@Autowired
	private DeviceCmdService deviceCmdService;
	@Autowired
	private F18DeviceService f18DeviceService;
	
	
	private String stamp="0",OpStamp="0";
	@RequestMapping("/cdata")
	public void cdata(HttpServletRequest request, HttpServletResponse response) {
		try {
			String options = request.getParameter("options");
			String sn = request.getParameter("SN");
			System.out.println("sn: " + sn);
			System.out.println("options: " + options);
			System.out.println("stamp: " + request.getParameter("Stamp"));
			if(null!=request.getParameter("Stamp")&&(!"0".equals(request.getParameter("Stamp"))))
				stamp=request.getParameter("Stamp");
			System.out.println("OpStamp: " + request.getParameter("OpStamp"));
			if(null!=request.getParameter("OpStamp")&&(!"0".equals(request.getParameter("OpStamp"))))
				OpStamp=request.getParameter("OpStamp");
			String mathod=request.getMethod();
			if ("GET".equals(mathod)) {
				if (!clockService.isExistF18DeviceFromRedis(sn)) {
					//新设备注册
					F18Device f18Device=new F18Device();
					f18Device.setDeviceSn(sn);
					String ipString=getIpAddr(request);
					f18Device.setDeviceName(ipString);
					f18Device.setIp(ipString);
					f18Device.setDeviceOpStamp(OpStamp);
					f18Device.setDeviceStamp(stamp);
					clockService.regF18Device(f18Device);
				}else {
					//老设备注册
					F18Device f18Device=f18DeviceService.getF18DeviceFromRedis(sn);
					response.setCharacterEncoding("UTF-8");// 设置Response的编码方式为UTF-8
					response.addHeader("Content-Type", "text/plain");
					PrintWriter writer;
					writer = response.getWriter();
					writer.write("GET OPTION FROM:"+sn+"\r\n");
					writer.write("Stamp="+f18Device.getDeviceStamp()+"\r\n");
					writer.write("OpStamp="+f18Device.getDeviceOpStamp()+"\r\n");
					writer.write("ErrorDelay="+60+"\r\n");
					writer.write("Delay="+2+"\r\n");
					writer.write("TransTimes="+"00:00;01:00;02:00;03:00;04:00;05:00;06:00;07:00;08:00;09:00"+"\r\n");
					writer.write("TransInterval="+1+"\r\n");
					writer.write("TransFlag=1111000000"+"\r\n");
					writer.write("RealTime=1"+"\r\n");
					writer.write("Encrypt=0");
					writer.close();
				}
				
			}else {
				//更新OpStamp跟Stamp到redis中
				if (clockService.isExistF18DeviceFromRedis(sn)) {
					F18Device f18Device=f18DeviceService.getF18DeviceFromRedis(sn);
					if (null==stamp||stamp.equals("0")) {
						stamp=f18Device.getDeviceStamp();
					}
					if (null==OpStamp||OpStamp.equals("0")) {
						OpStamp=f18Device.getDeviceOpStamp();
					}
					f18Device.setDeviceOpStamp(OpStamp);
					f18Device.setDeviceStamp(stamp);
					clockService.regF18Device(f18Device);
				}
				//发送过来的考勤数据，开门记录
				String logDataString=getStreamData(request);
				System.out.println("设备post上来的内容："+logDataString);
				if (!"".equals(logDataString)) {
					f18DeviceService.saveLogDataToRedis(logDataString,sn);
				}
				System.out.println("cdata:"+logDataString);
				writeCmd(response,"OK");
			}
			f18DeviceService.UpdateDeviceOnLine(sn);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//发送命令给设备
	@RequestMapping("/getrequest")
	public void getRequest(HttpServletRequest request,
			HttpServletResponse response) {
		String sn=request.getParameter("SN");
		String infoString=request.getParameter("INFO");//固件版本号、人数，考勤记录数等信息
		System.out.println("sn: " + sn);
		System.out.println("INFO: " +infoString);
		//发送重启命令
		String cmdString="C:1:CHECK\r\n";
		//cmdString+="C:2:CLEAR LOG";//清理开门记录
		//cmdString+="\r\nC:3:CLEAR DATA";//清理所有数据，包括人员数据
		
		//cmdString+="C:4:INFO\r\n";//发送设备信息给软件
		cmdString+="C:5:SET OPTION IPAdress=192.168.1.221\r\n";//设置设备IP为：192.168.1.221
		
		//cmdString+="\r\nC:6:REBOOT";//发送重启命令给设备
		//cmdString+="C:7:RELOAD OPTIONS\r\n";
		//发送人的命令
		/*String userString="";
		userString=userString.format("USER PIN=%d\tName=%s\tPri=%d\tPasswd=%s\tCard=[%s]\tGrp=%d\tTZ=%s", 123,
				"李培峰",0,"","0000000000",1,"0000000000000000");
		cmdString+="C:8:DATA "+userString+"\r\n";
		//发送指纹命令
		String fpString="";
		fpString=fpString.format("FP PIN=%d\tFID=%d\tSize=%d\tValid=%d\tTMP=%s",
				123,0,1172,1,"Si1TUzIxAAADbm4ECAUHCc7QAAAbb2kBAAAAg5MYZ25TAIAPjQCdAAxhjABgAIkPHwCDbpUPZwCVAMEPHm6fAF4P1QBsAJZhiwCuAIAP7ACybusPnQDFAEYPl27aAHsPyAAZAJJhdwDkAGYPhwDkblsPWAACAYoPxW4XAZkPkgDZASZhcwAhATsP4wBHb0cPiwBEAeYOOm5KAUIPYQCRAShhnABZAaMOHgBjb5YPCnIO+4Z/s+T7kssPuH5DC1DpMwJ/D4OHU4dUET6HTXYfX5YHsWw2BVsXJvxffzhqQI7Hk4friAqhahL01fp6FHr8hH5yGbv9Euy7GwCLTw0n9ddzE/VVeBPrZ3WrC4p71YKnBluNQhgv7m11SAVHHxf7RIMlbAfrzf1KGuIL4YRLCyfygYOme5TtbvefA3t35/QXTjIBAi0fO8IAjFESXWUMAFuFA/2RbD7C/QUAkUgAk3IDAC9MdwcGAyFQesDDbgfFkVVnP0sHAI9c1cDDkUgHAGdYegVxwmgBD4LkQP/IAHcNCML9VMBTiQYDfI3pwP9HDcVxaGdWwET/wf4FEAMFlwBAwD5Tj8AEbhKY6cDAwDr9Em5hdf1A/8D7W0evBABmmXqGwAAj8uP/Nw4AfLoDLCj+ZEYDABxnWv1mAdKolmdpzwBs6YGAwsJlDMVvrhnAwcHBwXhBEQMyvvpG/zL/kP/DDgwAXMVxwgWDexYVAJjFhoBGwMKshcBlmBkAz87ZKsH9LzDAOwTB/CJFGAAS0Nw6/sOQwf7B/f/+j//DKMHARxAAkB2DkKpwwX5rCwAG25CuwJTCwoIMxZjfZ0E+XcEKALfibqyBg8ALAD4iYMGuiljCAwB0LWnBZQFC61zBhbNZGG4D+ND+/sEFMUVAw/5MTFfAzRBXbFJ+wYcIEJwGTK95hw8RFRFnwGmuwGZswQ0AqrV5rH5+wsDBwNUQxnyfwcLBqsOww5VgEcIYl/+YA8PHrcHDhgoQld8X/TbAwf/ECBAPGiMdwE0IEJMg4Vx3aBFxJj3Ci98RFUahwVr+wsAA/MEZwnnBwsFuBBkSekGewMBZ/wV+wPnCw3x5wQPVI0QiwBkRFU2ek8DDNsP/xJ/DkAbAwK3AFRCuX6AFwC2V+vj7//9KtlsXfs5jlsH9VDr69pkqwP/DZAA=");
		cmdString+="C:9:DATA "+fpString+"\r\n";
		*/
		System.out.println(cmdString);
		//删除人的命令
		String sendString=null;
		try {
			sendString = deviceCmdService.getUnExecCmd(sn);
		} catch (Exception e) {
			logger.error("获取命令出错");
		}
		//String sendString=clockService.sendCmdToDevice(sn,deviceCmdService.getCheckCmd());
		if (null!=sendString) {
			writeCmd(response,sendString);
		}
		//writeCmd(response,cmdString);
		f18DeviceService.UpdateDeviceOnLine(sn);
	}
	//获取命令执行结果
	@RequestMapping("/devicecmd")
	public void deviceCmd(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String sn=request.getParameter("SN");
		System.out.println("sn: " + sn);
		String retString=getStreamData(request);
		System.out.println("devicecmd:"+retString);
		clockService.dealDeviceCmd(sn,retString);
		writeCmd(response,"OK");
		f18DeviceService.UpdateDeviceOnLine(sn);
	}
	
	
	private void writeCmd(HttpServletResponse response,String cmd) {
		try {
			response.setCharacterEncoding("GB2312");// 设置Response的编码方式为UTF-8
			response.addHeader("Content-Type", "text/plain;charset=GB2312");
			PrintWriter writer;
			writer = response.getWriter();
			writer.write(cmd);
			writer.close();
		} catch (Exception e) {
			
		}
	}
	public static String getStreamData(HttpServletRequest request) throws IOException
	{
		StringBuilder bufferData = new StringBuilder();
		BufferedReader br = null;
		try
		{
			request.setCharacterEncoding("GB2312");
			ServletInputStream inputStream=request.getInputStream();
			br = new BufferedReader(new InputStreamReader(inputStream, "GB2312"));
			char[] cbuf=new char[1024];
			while((br.read(cbuf))!=-1){
				bufferData.append(cbuf);
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
		finally
		{
			if(br != null)
			{
				br.close();
			}
		}
		return bufferData.toString().trim();
	}
	public String getIpAddr(HttpServletRequest request) { 
	       String ip = request.getHeader("x-forwarded-for"); 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       return ip; 
	   } 
}
